/*
 * WSConnectionManager.java
 *
 * Created on March 13, 2007, 9:09 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ca.uvic.group2.testHarness;
import java.net.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author pat
 */
public class WSConnectionManager {
   private HttpURLConnection conn;
   private URL url;

   /** Creates a new instance of WSConnectionManager */
    public WSConnectionManager() {
        try {
            String host = System.getProperty("group2.tomcatHost", "localhost");
            if(host.indexOf(",") != -1)
               host = host.substring(0, host.indexOf(","));
            System.out.println("Tomcat is at " + host);
            url = new URL("http://" + host + ":46202/stockserv/stockserv");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setInstanceFollowRedirects(false);
            conn.setAllowUserInteraction(false);
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded" );
            conn.setDoOutput(true);
            conn.setDoInput(true);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (ProtocolException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private boolean command(String cmd) {
        String data = "cmd=" + cmd;
        boolean result = false;
        try {
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            System.out.println(data);
            wr.write(data);
            wr.flush();
            wr.close();

            byte[] buffer = new byte[1024];
            InputStream input = conn.getInputStream();
            int len;

            while ((len = input.read(buffer)) > 0) {
                ;
            }

            input.close();
        } catch(IOException e) {
            e.printStackTrace();
        }//endTryCatch
        return result;
    }

    public boolean commandUserInit(String user) {
       String data = "cmd=login&username="+ user +"&passward=pass";
       HashMap sessions = new HashMap();
       String sessionID;
      try {
         for(int j=0 ; j<2; j++) {
             // Send data
             String host = System.getProperty("group2.tomcatHost", "localhost");
             if(host.indexOf(",") != -1)
                host = host.substring(0, host.indexOf(","));

             URL url = new URL("http://" + host + ":46202/stockserv/stockserv");
             System.out.println("Iteration " + j + " url " + url);
             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
             conn.setRequestMethod("POST");
             conn.setInstanceFollowRedirects(false);
             conn.setAllowUserInteraction(false);
             conn.setRequestProperty( "Content-type", "application/x-www-form-urlencoded" );
             conn.setDoOutput(true);
             conn.setDoInput(true);
             conn.setRequestProperty( "Content-length", Integer.toString(data.length()));
             if(sessions.containsKey(user)) {
                 System.out.println("Cookie: " + sessions.get(user));
                 conn.setRequestProperty("Cookie", (String) sessions.get(user));
             }
             OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
             wr.write(data);
             wr.flush();
             wr.close();

             // Get the response
             if(!sessions.containsKey(user)) {
                 // Look for our cookie (there are two now)
                 for (int i = 1; i < 10; ++i) {
                     String key = conn.getHeaderFieldKey(i);
                     if (key == null) {
                         break;
                     }
                     if (key.equals("Set-Cookie")) {
                         String value = conn.getHeaderField(i);
                         System.out.println("Cookie value: " + value);
                         if (value.startsWith("sessionid")) {
                             // Found it.
                             sessionID = value.substring(0, value.indexOf(";"));
                             System.out.println("SESSIONID: " + sessionID);
                             sessions.put(user, sessionID);
                             break;
                         }
                     } else if (key.equals("Date")) {
                         // Cookie isn't there.
                         break;
                     }
                 }
             }

             BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
             String line;
             while ((line = rd.readLine()) != null) {
                 //debugLog.debug(line);
             }
             rd.close();
             data = "cmd=logout";
         }
       } catch (Exception e) {
          e.printStackTrace();
          return false;
       }
       return true;
    }

    public boolean commandInit() {
        return command("init");
    }//endMethod

    public boolean commandStopStats() {
        return command("statstop");
    }//endMethod

    public boolean commandDumplogStub() {
        return false;
    }

    public boolean commandDumplog() {
        String data = "cmd=dumplog&user=0";
        try {
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            System.out.println(data);
            wr.write(data);
            wr.flush();
            wr.close();

            int responseCode = conn.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                System.out.println("HTTP Error " + String.valueOf(responseCode));
                return false;
            }

            byte[] buffer = new byte[1024 * 64];
            int readLen;
            long bytesWritten = 0;

            // Create download file
            File downloadDir = new File(System.getProperty("group2.downloadDir", "/tmp"));
            downloadDir.mkdirs();
            File outputFile = new File(downloadDir, "testLog.gz");
            System.out.println("Writing log file to " + outputFile.getPath());

            // Get input and output streams
            InputStream input = conn.getInputStream();
            FileOutputStream output = new FileOutputStream(outputFile);

            // Read/Write streams
            while ((readLen = input.read(buffer)) > 0) {
                output.write(buffer, 0, readLen);
                bytesWritten += readLen;
            }

            System.out.println("Log written. " + bytesWritten + " bytes");

            output.close();
            input.close();
        } catch(IOException e) {
            //debugLog.debug("Exception in DUMPLOG");
            e.printStackTrace();
            return false;
        }//endTryCatch
        return true;
    }//endMethod
}
